#include "TcpServer.h"
#include "TcpSocket.h"

TcpServer::TcpServer()
{
}

namespace
{
    std::vector<std::thread> m_conn_threads;
};

void TcpServer::Listen(uint32_t port)
{
    struct sockaddr_in servaddr, cliaddr; // 定义服务器与客户端地址结构体
    socklen_t cliaddr_len;                // 客户端地址长度
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    memset(&servaddr, 0, sizeof(servaddr)); // 将服务器端口地址清零
    servaddr.sin_family = AF_INET;
    servaddr.sin_addr.s_addr = htonl(INADDR_ANY);
    servaddr.sin_port = htons(port);
    int bind_res = bind(sockfd, (struct sockaddr *)&servaddr, sizeof(servaddr));
    int listen_res = listen(sockfd, 20);

    LOGI("bind res %d", bind_res);
    LOGI("listen %d", listen_res);
    if (listen_res)
    {
    }

    while (1)
    {
        struct sockaddr_in cliaddr;
        socklen_t cliaddr_len; // 客户端地址长度
        cliaddr_len = sizeof(cliaddr);
        int connfd = accept(sockfd, (struct sockaddr *)&cliaddr, &cliaddr_len);

        LOGI("new connetion", "");
        TcpSocket *newSocket = new TcpSocket(connfd, cliaddr);

        if (this->on_accept)
        {
            auto th = [&]()
            {
                on_accept(newSocket);
            };

            m_conn_threads.push_back(std::thread(th));
        }
    }
}

void TcpServer::SetOnAccept(std::function<void(TcpSocket *)> on_accecpt)
{
    this->on_accept = on_accecpt;
}

void TcpServer::OnClose()
{
    close(sockfd);
    for (auto &th : m_conn_threads)
    {
        if (th.joinable())
        {
            th.join();
        }
    }
}
